/* eslint-disable @typescript-eslint/no-explicit-any */
import { Button, Input, message, Table } from "antd";
import Form from "antd/es/form";
import styles from "./group.module.less";
import { ColumnsType } from "antd/es/table";
import { useForm } from "antd/es/form/Form";
import { useEffect, useMemo, useState } from "react";
import { chatroomList } from "../../interfaces";
import { MembersModal } from "./membersModal";
import { AddMemberModal } from "./addMemberModal";
import { CreateGroupModal } from "./createGroupModal";
import { Navigate, useNavigate } from "react-router-dom";

interface SearchGroup {
  name: string;
}

interface GroupSearchResult {
  id: number;
  name: string;
  type: boolean;
  userCount: number;
  userIds: Array<number>;
  createTime: Date;
}

function Group() {
  const [groupResult, setGroupResult] = useState<Array<GroupSearchResult>>();
  const [isMembersModalOpen, setMembersModalOpen] = useState(false);
  const [isAddMemberModalOpen, setAddMemberModalOpen] = useState(false);
  const [isCreateGroupModalOpen, setCreateGroupModalOpen] = useState(false);

  const [chatroomId, setChatroomId] = useState<number>(-1);
  const [queryKey, setQueryKey] = useState<string>("");
  const [form] = useForm();
  const navigate = useNavigate();

  useEffect(() => {
    searchGroup({
      name: form.getFieldValue("name"),
    });
  }, []);

  const columns: ColumnsType<GroupSearchResult> = useMemo(
    () => [
      {
        title: "名称",
        dataIndex: "name",
      },
      {
        title: "创建时间",
        dataIndex: "createTime",
        render: (_, record) => {
          return new Date(record.createTime).toLocaleString();
        },
      },
      {
        title: "人数",
        dataIndex: "userCount",
      },
      {
        title: "操作",
        render: (_, record) => (
          <div>
            <a
              href=""
              onClick={() => {
                navigate("/chat", {
                  state: {
                    chatroomId: record.id,
                  },
                });
              }}
            >
              聊天
            </a>
            &nbsp;
            <a
              href="#"
              onClick={() => {
                setChatroomId(record.id);
                setMembersModalOpen(true);
              }}
            >
              详情
            </a>
            &nbsp;
            <a
              href="#"
              onClick={() => {
                setChatroomId(record.id);
                setAddMemberModalOpen(true);
              }}
            >
              添加成员
            </a>
          </div>
        ),
      },
    ],
    []
  );

  const searchGroup = async (values: SearchGroup) => {
    try {
      const res = await chatroomList(values.name || "");
      if (res.status === 201 || res.status === 200) {
        setGroupResult(
          res.data
            .filter((item: GroupSearchResult) => {
              return item.type === true;
            })
            .map((item: GroupSearchResult) => {
              return {
                ...item,
                key: item.id,
              };
            })
        );
      }
    } catch (e: any) {
      message.error(e.response?.data?.message || "请求失败");
    }
  };

  return (
    <div id={styles.container}>
      <div className={styles.friendship_form}>
        <Form
          form={form}
          onFinish={searchGroup}
          name="search"
          layout="inline"
          colon={false}
        >
          <Form.Item label="名称" name="name">
            {/* 没有绑定name导致搜不出来。。 */}
            <Input />
          </Form.Item>

          <Form.Item label=" ">
            <Button type="primary" htmlType="submit" className={styles.btn}>
              搜索
            </Button>
          </Form.Item>
          <Form.Item label=" ">
            <Button
              className={styles.btn}
              type="primary"
              onClick={() => {
                setCreateGroupModalOpen(true);
              }}
            >
              创建群聊
            </Button>
          </Form.Item>
        </Form>
      </div>
      <div className={styles.friendship_table}>
        <Table columns={columns} dataSource={groupResult} />
      </div>

      <MembersModal
        isOpen={isMembersModalOpen}
        chatroomId={chatroomId}
        queryKey={queryKey}
        handleClose={() => {
          setMembersModalOpen(false);
        }}
      />
      <div>
        <AddMemberModal
          isOpen={isAddMemberModalOpen}
          chatroomId={chatroomId}
          handleClose={() => {
            setAddMemberModalOpen(false);
            //设置随机值变化触发useeffect重新渲染
            setQueryKey(Math.random().toString().slice(2, 10));
            searchGroup({
              name: form.getFieldValue("name"),
            });
          }}
        />
      </div>
      <div>
        <CreateGroupModal
          isOpen={isCreateGroupModalOpen}
          handleClose={() => {
            setCreateGroupModalOpen(false);
            searchGroup({
              name: form.getFieldValue("name"),
            });
          }}
        ></CreateGroupModal>
      </div>
    </div>
  );
}

export default Group;
